var stepProcess = {
    // 当前实例配置
    options: {},
};

(function ($) {
    $.extend({
        step: {
            init: function (options) {
                var defaults = {
                    id: "simple-process",
                    data: {
                        class: "step.CustomModel",
                        linkFromPortIdProperty: "fromPort",
                        linkToPortIdProperty: "toPort",
                        nodeDataArray: [
                            {
                                key: 'Start',
                                text:'开始',
                                category:'Start',
                                obj:'',
                                choice: [],
                                joinSign:'',
                                isLeader:'',
                                remark:''
                            },
                            {
                                key:'End',
                                text:'结束',
                                category:'End',
                                obj:'',
                                choice: [],
                                joinSign:'',
                                isLeader:'',
                                remark:''
                            }
                        ],
                        linkDataArray: [
                            {
                                from: 'Start',
                                to: 'End',
                                fromPort: 'R',
                                toPort: 'L'
                            }
                        ]
                    },
                    currentNode: null,
                    isModified: true
                };
                var options = $.extend(defaults, options);
                stepProcess.options = options;
                $.ospProces = $('#' + options.id).osfwStepProcess({
                    data: options.data,                 // 构造流程的数据对象
                    currentNode: options.currentNode,   // 当前流转的流程节点
                    isModified: options.isModified,     // 流程是否可编辑修改
                    callback: options.callback,
                });
            },
            // 上一步
            previousStep: function () {
                $.ospProces.osfwStepProcess("previous");
            },
            // 下一步
            nextStep: function () {
                $.ospProces.osfwStepProcess("next");
            },
            // 指定步
            gotoStep: function (step) {
                $.ospProces.osfwStepProcess("goto", step);
            },
            // 新增节点
            insertStep: function (obj) {
                var from_ = $(obj).data("key");
                $.modal.prompt("添加节点", "请输入您要新建的节点名称：", "", "text", function (data) {
                    var key = Date.now().toString(36);
                    var nodeData_ = {
                        key: key || '',
                        text: data || '节点',
                        category: 'Default',
                        obj: '',
                        choice: [],
                        joinSign: '0',
                        isLeader: '1',
                        remark: ''
                    };
                    $.ospProces.osfwStepProcess("insert", from_, nodeData_);
                    $.step.addName($.ospProces.data_obj);
                });
            },
            // 编辑节点
            editStep: function (obj) {
                var key = $(obj).data("key");
                $('.fw-layout-right .foldbar-outdent').click();
                $.form.clear('form-node-info');
                $('#form-node-info').removeClass('am-hide');
                var nodeData = $.grep($.ospProces.data_obj.nodeDataArray, function(item) {return item.key == key;})[0];
                $.step.bindForm("form-node-info", nodeData);
            },
            // 切换节点
            switchStep: function (obj) {
                if(!$('#form-node-info').hasClass('am-hide')) {
                    $.form.clear('form-node-info');
                    var key = $(obj).data("key");
                    var nodeData = $.grep($.ospProces.data_obj.nodeDataArray, function(item) {return item.key == key;})[0];
                    $.step.bindForm("form-node-info", nodeData);
                }
            },
            // 删除节点
            removeStep:function (obj) {
                $.modal.confirm("确认要删除[ " + $(obj).data("name")  + " ]节点吗？", function () {
                    $.ospProces.osfwStepProcess("remove", $(obj).data("key"));
                    $.step.addName($.ospProces.data_obj);
                    $.form.clear('form-node-info');
                    $('#form-node-info').addClass('am-hide');
                    $('.fw-layout-right .foldbar-indent').click();
                });
            },
            // 向前移动
            leftMoveStep: function (obj) {
                $.ospProces.osfwStepProcess("leftMove", $(obj).data("key"));
                $.step.addName($.ospProces.data_obj);
            },
            // 向后移动
            rightMoveStep: function (obj) {
                $.ospProces.osfwStepProcess("rightMove", $(obj).data("key"));
                $.step.addName($.ospProces.data_obj);
            },
            addName: function (data) {
                if($.common.isEmpty($("input[name=procKey]").val()) || $("input[name=procKey]").attr("data-custom") == "false") {
                    $("input[name=procKey]").val(Date.now().toString(12));
                }
                if($.common.isEmpty($("input[name=procName]").val()) || $("input[name=procName]").attr("data-custom") == "false") {
                    var names = "";
                    var nextNodeKey;
                    if(data.nodeDataArray.length > 2) {
                        for(var i = 0; i < data.nodeDataArray.length; i++) {
                            // 找下一个节点
                            var nodeData, linkData;
                            if(i == 0) {
                                nodeData = $.grep(data.nodeDataArray, function (item) { return item.category == 'Start'; })[0];
                            }else {
                                nodeData = $.grep(data.nodeDataArray, function (item) { return item.key == nextNodeKey; })[0];
                            }
                            if(nodeData.category != 'Start' && nodeData.category != 'End') {
                                if(i == 1) {
                                    names += nodeData.text
                                }else {
                                    names += "⇢" + nodeData.text
                                }
                            }
                            // 设置下一节点key
                            if(nodeData.category != 'End') {
                                linkData = $.grep(data.linkDataArray, function (item) { return item.from == nodeData.key; })[0];
                                nextNodeKey = linkData.to;
                            }
                        }
                        if($.common.isNotEmpty(names)) {
                            $("input[name=procName]").val(names);
                        }
                    }
                }
            },
            bindForm: function (formId, data) {//绑定数据给表单
                data.newKey = data.key;
                for (items in data) {
                    var dd = $("#" + formId + " [name^='" + items + "']")[0];
                    if (dd != null && dd.nodeName == 'INPUT') {
                        var ty = $(dd).attr("type");
                        if (ty != null && ty == "radio") {
                            $(dd).removeAttr("checked");
                            $("[name=" + items + "][value=" + data[items] + "]").attr("checked", true);

                        } else if (ty != null && ty == "checkbox") {
                            $(dd).removeAttr("checked");
                            var strdata = data[items].split("%&");
                            for (var k = 0; k < strdata.length; k++) {
                                $("[name=" + items + "][value=" + data[items] + "]").attr("checked", true);
                            }
                        } else {
                            if (typeof data[items] === "string") {
                                $(dd).val(data[items]);
                            } else {
                                $(dd).val(JSON.stringify(data[items]));
                            }
                        }
                    }else if(dd != null && dd.nodeName == 'TEXTAREA') {
                        $(dd).text(data[items]);
                    }else if(dd != null && dd.nodeName == 'SELECT') {
                        $(dd).find("option").removeAttr("selected");
                        $(dd).find("option[value='"+data[items]+"']").attr("selected", true);
                    }
                }
                initOper();
            },
            editStepCallback: function (nodeForm) {
                console.log("修改节点信息1："+nodeForm);
                nodeForm.choice = nodeForm.choice == "" ? [] : $.parseJSON(nodeForm.choice);
                $.ospProces.osfwStepProcess("edit", nodeForm);
                console.log("修改节点信息2："+$.ospProces.data_obj)
                $("#form-node-info input[name=key]").val(nodeForm.key);
                $.step.addName($.ospProces.data_obj);
            },
            toJson: function () {
                return $.ospProces.osfwStepProcess("toJson");
            }
        },
    });
})(jQuery);


